
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index';

Vue.use(VueRouter)

// 如果要访问的地址包含在权限里面 可以访问 
function hasUrl(url, next) {
  // console.log(store.getters.getUserInfo.menus_url);
  // 获取当前账号可以访问的路由
  let result = store.getters.getUserInfo.menus_url;
  // console.log(result);
  let res = result.some(item => {
    return item == url
  })
  if (res) {
    // 如果访问的地址在权限里  直接next跳转
    next();
    return;
  } else {
    // 否则强制跳转首页
    next('/home')
  }

}


export const IndexRouter = [
  {
    path: '/home',
    component: () => import('../views/home.vue')
  },
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    // 路由独享守卫  beforeEnter
    beforeEnter(to, from, next) {
      hasUrl('/menu', next);
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '用户管理'
    },
    // 路由独享守卫  beforeEnter
    beforeEnter(to, from, next) {
      hasUrl('/menu', next);
    }
  },
  {
    path: '/user',
    component: () => import('../views/user/user.vue'),
    meta: {
      title: '管理员管理'
    },
    // 路由独享守卫  beforeEnter
    beforeEnter(to, from, next) {
      hasUrl('/menu', next);
    }
  },
  {
    path: '/cate',
    component: () => import('../views/cate/cate.vue'),
    meta: {
      title: '商品分类'
    }
  },
  {
    path: '/specs',
    component: () => import('../views/specs/specs.vue'),
    meta: {
      title: '商品规格'
    }
  },
  {
    path: '/goods',
    component: () => import('../views/goods/goods.vue'),
    meta: {
      title: '商品管理'
    }
  },
  {
    path: '/member',
    component: () => import('../views/member/member.vue'),
    meta: {
      title: '会员管理'
    }
  },
  {
    path: '/banner',
    component: () => import('../views/banner/banner.vue'),
    meta: {
      title: '轮播图管理'
    }
  },
  {
    path: '/seck',
    component: () => import('../views/seck/seck.vue'),
    meta: {
      title: '秒杀活动'
    }
  },
]
const routes = [
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      ...IndexRouter,
      // 二级路由重定向
      {
        path: '',
        redirect: '/index'
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    // 一级路由重定向
    path: '*',
    redirect: '/login'
  }

]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,

})
// 全局路由导航守卫
router.beforeEach((to, from, next) => {
  // to and  from are both route objects. must call `next`.
  // 如果去到登录页  直接next
  if (to.path == '/login') {
    next();
    return;
  } else if (store.getters.getUserInfo) {
    // 如果已经登录 next
    next();
    return;
  } else {
    // 如果没有登录  强制跳转登录页
    next('/login')
  }

})
export default router

